import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from '@/router'
import store from '@/store'

const whiteList = ['/login', '/404']

router.beforeEach(async(to, from, next) => {
  // to去哪里
  // from从哪里来
  // next放行
  NProgress.start()

  const token = store.getters.token
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      // 判断是否获取过用户信息
      // 如果获取过就直接放行，没有获取就获取
      if (!store.getters.userId) {
        await store.dispatch('user/getUserInfo')
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }

  NProgress.done()
})
